package boot

import (
	"hertz/demo/biz/db"
	"hertz/demo/biz/model"

	"github.com/spf13/viper"
	"gorm.io/gorm"
)

func InitDB() *gorm.DB {
	dbPath := viper.GetString("db.path")
	if dbPath == "" {
		panic("db.path is undefined in config")
	}
	var err error

	database, err := db.OpenDB(dbPath)
	if err != nil {
		panic("failed to connect database")
	}

	model.MigrateDB(database)

	users, err := model.ListUser(database)
	if err != nil {
		panic("can't check user table")
	}
	username := viper.GetString("user.default_root_user")
	if username == "" {
		panic("can't get user.default_root_user")
	}
	password := viper.GetString("user.default_root_password")
	if username == "" {
		panic("can't get user.default_root_password")
	}
	if len(users) == 0 {
		err = model.AddUser(database, &model.User{Username: username, Password: password, IsAdmin: true, Disable: false})
		if err != nil {
			panic("add root user failed")
		}
	}
	return database
}
